import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '../router/index'
import qs from 'qs'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.loading =
      config.showScreenLoading &&
      Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    // console.log('===============', config)
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['authorization'] = getToken()
    }
    const contentType = config.headers['Content-Type']
    if (/x-www-form-urlencoded/.test(contentType)) {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const { data, config } = response
    const res = data.body
    const header = data.heads
    config.loading && config.loading.close()
    if (config.export) return data
    if ((header && header.code === 16019) || (header && header.code === 5003)) {
      return res || header || response
    } else if (header && header.code !== 200) {
      // 需要获取header里的错误码
      if (config.hideError) return { ...res, ...header }
      // 无权限
      switch (header.code) {
        case 403: // 无权操作
          router.app.$router.push({ path: '/401' })
          break
        case 401: // token失效
          MessageBox.confirm('您的登录已失效，重新登陆？', '提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          break
        // case 300:
        //   Message({
        //     message: '业务异常',
        //     type: 'error',
        //     duration: 5 * 1000
        //   })
        //   break
        case 1999:
          Message({
            message: '系统异常',
            type: 'error',
            duration: 5 * 1000
          })
          break
        default:
          if (config.hideError) return { ...res, ...header }
          Message({
            message: header.message || 'Error',
            type: 'error',
            duration: 4 * 1000
          })
          break
      }
      return Promise.reject(new Error(header.message || 'Error'))
    } else {
      return res || header || response
    }
  },
  error => {
    console.log('错误' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
